<?php

namespace app\admin\controller\admin;

use app\common\controller\AdminController;
use app\common\services\annotation\ControllerAnnotation;
use app\common\services\annotation\NodeAnnotation;
use Juhelib\excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use support\Request;
use support\Response;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="order")
 */
class OrderController extends AdminController
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Order();
    }

    /**
     * @NodeAnnotation(title="列表")
     */
    public function index(Request $request): Response
    {
        list($page, $limit, $where) = $this->buildTableParams();

        $activity_id = $request->get('activity_id');
        if (!$request->isAjax()) {
            return $this->fetch('', ['activityId' => $activity_id]);
        }
        if ($request->input('selectFields')) {
            return $this->selectList();
        }

        // 获取所有员工数据
        $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $activity_id, 'role' => 2])->column('user_id');

        $where[] = ['a.order_status', '=', 2];
        $where[] = ['a.activity_id', '=', $activity_id];
        $count = $this->model
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->join('activity c', 'a.activity_id = c.id', 'left')
            ->field('a.*, b.nickname, b.openid, c.activity_title')
            ->where($where)
            ->count();
        $list  = $this->model
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->join('activity c', 'a.activity_id = c.id', 'left')
            ->field('a.*, b.nickname, b.openid, c.activity_title')
            ->where($where)
            ->order($this->order)->page($page, $limit)->select()->toArray();
        foreach ($list as &$value) {
            // 是否为员工直推
            $value['is_clerk_recom'] = in_array($value['recom_user_id'], $clerk_user_ids) ? 1 : 0;
        }
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="详情")
     */
    public function info(Request $request): Response
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);

        $staff = Db::name('user')->where(['id' => $row['clerk_user_id'] ?? ''])->find();
        $recom = Db::name('order')
            ->alias('a')
            ->leftJoin('user b', 'a.user_id = b.id')
            ->where(['a.activity_id' => $row['activity_id'], 'a.user_id' => $row['recom_user_id']])
            ->field('a.*, b.nickname, b.avatar_url')
            ->find();
        return $this->fetch('', [
            'id' => $id,
            'row' => $row,
            'staff' => $staff,
            'recom' => $recom,
        ]);
    }

    /**
     * @NodeAnnotation(title="直推人员")
     */
    public function direct_recom(Request $request): Response
    {
        $id  = (int)$request->input('id');
        $row = $this->model->find($id);
        list($page, $limit) = $this->buildTableParams();
        $count = $this->model
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->where(['a.activity_id' => $row['activity_id'], 'a.recom_user_id' => $row['user_id']])
            ->field('a.*, b.avatar_url, b.nickname, b.openid')
            ->count();
        $list  = $this->model
            ->alias('a')
            ->join('user b', 'a.user_id = b.id', 'left')
            ->where(['a.activity_id' => $row['activity_id'], 'a.recom_user_id' => $row['user_id']])
            ->field('a.*, b.avatar_url, b.nickname, b.openid')
            ->order($this->order)->page($page, $limit)->select()->toArray();
        $data  = [
            'code'  => 0,
            'msg'   => '',
            'count' => $count,
            'data'  => $list,
        ];
        return json($data);
    }

    /**
     * @NodeAnnotation(title="导出")
     */
    public function export(Request $request): Response|bool
    {
        try {
            list($page, $limit, $where) = $this->buildTableParams();

            $activity_id = $request->get('activity_id');
            $where[] = ['a.order_status', '=', 2];
            $where[] = ['a.activity_id', '=', $activity_id];

            // 获取所有员工数据
            $clerk_user_ids = Db::name('activity_user_role')->where(['activity_id' => $activity_id, 'role' => 2])->column('user_id');

            $list  = $this->model
                ->alias('a')
                ->join('user b', 'a.user_id = b.id', 'left')
                ->join('activity c', 'a.activity_id = c.id', 'left')
                ->field('a.*, b.nickname, b.openid, c.activity_title')
                ->where($where)
                ->order($this->order)->select()->toArray();
            foreach ($list as $key => $value) {
                $excelData[$key] = [
                    $value['pay_no'] ?? '', $value['total_price'] ?? '', $value['nickname'] ?? '', $value['name'] ?? '', $value['phone'] ?? '', $value['customer_type'] ?? '', (in_array($value['recom_user_id'], $clerk_user_ids) ? '员工直推' : '非直推'), $value['openid'] ?? '', $value['activity_title'] ?? '', $value['pay_time'] ?? ''
                ];
            }
            $spreadsheet = excel::handleExcel([[
                'name' => '收款明细',
                'title' => [
                    '支付编号', '收款金额', '昵称', '姓名', '手机号', '新客/老客', '员工直推/非直推', 'OPENID', '所属活动', '收款时间'
                ],
                'data' => $excelData ?? []
            ]], []);
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

            $file_name = '收款明细';
            $file_path = runtime_path() . '/excel/' . $file_name . time() . '.' . mt_rand(100000, 999999) . '.xlsx';
            // 保存文件到 public 下
            @mkdir(runtime_path() . '/excel/');
            $writer->save($file_path);
            // 下载文件
            return response()->download($file_path, $file_name . '.xlsx');
        } catch (\Exception|\PhpOffice\PhpSpreadsheet\Exception$e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * @NodeAnnotation(title="退款")
     */
    public function refund(Request $request)
    {
        $id  = (int)$request->input('id');
        $data = $this->model->find($id);
        if ($data['order_status'] == 2 && $data['refund_status'] == 0) {
            try {
                (new \app\api\controller\OrderController)->refund($data['activity_id'], $data['user_id']);
            } catch (\Exception $error) {
                $error_remark = $error->getMessage();
            }
        } else {
            $error_remark = '数据异常，请刷新后重试！';
        }
        return empty($error_remark) ? $this->success('退款成功') : $this->error('退款失败！'.$error_remark);
    }
}
